import {h, markRaw} from 'vue';
import { deepConvert } from 'dlsjs';
import { isTerminator, transValue } from './TansRule';
import EditorSkeleton from '../EditorSkeleton.vue';
import { getTags } from "../../common/getConfig.js"

/**
 * 创建props属性
 * @return {Promise<void>}
 */
export function transVnode(unitOption, props) {
  return deepConvert(unitOption, props, transValue , isTerminator)
}

/**
 * 创建children属性
 * @param children
 * @param props
 */
export function createChildren(children, props) {
  if(!children) return null
  let childrenArr = []
  let childrenSlot = {}
  // 如果子属性含有@slot属性名，那么这些子节点当作插槽传递
  if(Array.isArray(children) && typeof props.parent.type !== 'string') {
    let childrenObj = {}
    // 根据@slot进行分组，同一插槽内可能存在多个节点
    for (let unit of children) {
      if(!unit.type) {
        // 没有type属性，就不是标签，不渲染
        continue
      }
      if(unit['@slot']) {
        let slotName = unit['@slot']
        if(!childrenObj[slotName]) childrenObj[slotName] = []
        childrenObj[slotName].push(unit)
      }else {
        if(!childrenObj.default) childrenObj.default = []
        childrenObj.default.push(unit)
      }
    }
    // 使用分组后的内容生成渲染函数（插槽要以函数形式传递）
    for(let slotName in childrenObj) {
      childrenSlot[slotName] = (slotScope) => {
        let arr = []
        for(let unit of childrenObj[slotName]) {
          if (typeof unit === 'object') {
              arr.push(h(EditorSkeleton, {vnode: unit, dataScope: props.dataScope, refScope: props.refScope, slotScope: slotScope, funcScope: props.funcScope}))
          }else {
            arr.push(unit)
          }
        }
        return arr
      }
    }
    return childrenSlot
  }
  // 当作普通子节点渲染
  else if(Array.isArray(children)) {
    for (let unit of children) {
      if (typeof unit === 'object') {
          childrenArr.push(h(EditorSkeleton, {vnode: unit, dataScope: props.dataScope, refScope: props.refScope, slotScope: props.slotScope, funcScope: props.funcScope}))
      } else {
        childrenArr.push(unit)
      }
    }
    return childrenArr
  }
  // 当作单节点文本内容渲染
  else {
    return children
  }
}

/**
 * 创建Type
 * @param typeKey
 * @param params
 * @return {*}
 */
export function createType(typeKey, params) {
  const tags = getTags()
  return markRaw(tags[typeKey] || typeKey)
}
